package CodeServlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@WebServlet("/coder")
public class CoderServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
    private Random random = new Random();
    private Color[] colors = {Color.gray, Color.green, Color.cyan};

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //响应对象返回的是图片
         response.setContentType("image/png");
         //在内存中创建一张图片
         BufferedImage bi = new BufferedImage(140, 45,
                   BufferedImage.TYPE_INT_RGB);
         //获取Graphic对象，用于绘制各种图案
         Graphics g = bi.getGraphics();
         //绘制填充的白色矩形
         g.setColor(Color.white);//设置画笔的颜色
         g.fillRect(0, 0, 140, 45);
         g.setColor(Color.black);
         g.drawRect(1, 1, 138, 43);
        
         //绘制干扰线
         g.setColor(Color.gray);
         for(int i = 0; i < 100; i ++){
              int x1 = random.nextInt(144) + 1;
              int y1 = random.nextInt(44) + 1;
              int x2 = random.nextInt(144) + 1;
              int y2 = random.nextInt(44) + 1;
              g.setColor(colors[random.nextInt(colors.length)]);
              g.drawLine(x1, y1, x2, y2);
         }
        
         //绘制随机验证码
         g.setColor(Color.red);
         g.setFont(new Font("隶书", Font.BOLD, 30));
         String c = "";
         for(int i = 0; i < 5; i ++){
              c += random.nextInt(10);
         }
         request.getSession().setAttribute("c", c);
         g.drawString(c, 20, 30);
        
         //向浏览器输出验证码图片
         JPEGImageEncoder jpeg = JPEGCodec
                   .createJPEGEncoder(
                             response.getOutputStream());
         jpeg.encode(bi);
    }

}
